// pages/adoption/adoption.js
const { post } = require('../../utils/request')
const { showSuccess, showError, showConfirm } = require('../../utils/util')

Page({
  data: {
    petId: null,
    petName: '',
    formData: {
      reason: '',
      address: '',
      environment: '',
      experience: '',
      phone: ''
    },
    submitting: false
  },

  onLoad(options) {
    const app = getApp()
    const userInfo = app.globalData.userInfo

    if (!userInfo) {
      showError('请先登录')
      wx.navigateBack()
      return
    }

    this.setData({
      petId: options.petId || null,
      petName: options.petName || '',
      'formData.phone': userInfo.phone || ''
    })

    // 设置页面标题
    if (options.petName) {
      wx.setNavigationBarTitle({
        title: `申请领养 - ${options.petName}`
      })
    }
  },

  // 领养理由输入
  onReasonInput(e) {
    this.setData({
      'formData.reason': e.detail.value
    })
  },

  // 居住地址输入
  onAddressInput(e) {
    this.setData({
      'formData.address': e.detail.value
    })
  },

  // 居住环境输入
  onEnvironmentInput(e) {
    this.setData({
      'formData.environment': e.detail.value
    })
  },

  // 养宠经验输入
  onExperienceInput(e) {
    this.setData({
      'formData.experience': e.detail.value
    })
  },

  // 联系电话输入
  onPhoneInput(e) {
    this.setData({
      'formData.phone': e.detail.value
    })
  },

  // 表单验证
  validateForm() {
    const { reason, address, environment, experience } = this.data.formData

    if (!reason.trim()) {
      showError('请填写领养理由')
      return false
    }

    if (reason.trim().length < 10) {
      showError('领养理由至少需要10个字符')
      return false
    }

    if (!address.trim()) {
      showError('请填写居住地址')
      return false
    }

    if (!environment.trim()) {
      showError('请描述居住环境')
      return false
    }

    if (!experience.trim()) {
      showError('请描述养宠经验')
      return false
    }

    return true
  },

  // 提交申请
  async onSubmit() {
    if (this.data.submitting) return

    if (!this.validateForm()) return

    try {
      await showConfirm('确认提交领养申请吗？')
    } catch {
      return
    }

    this.setData({ submitting: true })

    const app = getApp()
    const userInfo = app.globalData.userInfo

    const submitData = {
      petId: this.data.petId,
      petName: this.data.petName,
      userId: userInfo.id,
      userName: userInfo.name,
      phone: this.data.formData.phone || userInfo.phone,
      reason: this.data.formData.reason.trim(),
      address: this.data.formData.address.trim(),
      environment: this.data.formData.environment.trim(),
      experience: this.data.formData.experience.trim(),
      status: '待审核'
    }

    post('/adoption', submitData).then(res => {
      showSuccess('申请提交成功，请等待审核')
      
      // 延迟返回上一页
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)

    }).catch(err => {
      showError(err.msg || '提交失败，请重试')
    }).finally(() => {
      this.setData({ submitting: false })
    })
  }
})
